package com.summer.controller;

import com.alibaba.fastjson.JSONObject;
import com.summer.entity.PlatformUser;
import com.summer.entity.UserInfo;
import com.summer.util.RedisUtil;
import com.summer.variable.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class BaseController {

    @Resource
    private RedisUtil redisUtil;

    private static Logger LOG = LoggerFactory.getLogger(BaseController.class);

    /**
     * 得到 session
     *
     * @return
     */
    protected HttpSession getSession(HttpServletRequest request) {
        return request.getSession();
    }


    protected Object errorMsg(String msg) {
        if (msg == null || msg.isEmpty()) {
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", "1");
        map.put("message", msg);
        return map;
    }

    protected Object successMsg(String msg, Object obj) {
        if (msg == null || msg.isEmpty() || obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", "0");
        map.put("message", msg);
        map.put("data", obj);
        return map;
    }

    /**
     * 获得request中的参数
     *
     * @param request
     * @return string object类型的map
     */
    public HashMap<String, Object> getParametersO(HttpServletRequest request) {
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        if (request == null) {
            request = ((ServletRequestAttributes) RequestContextHolder
                    .getRequestAttributes()).getRequest();
        }
        Map req = request.getParameterMap();
        if ((req != null) && (!req.isEmpty())) {
            Map<String, Object> p = new HashMap<String, Object>();
            Collection keys = req.keySet();
            for (Iterator i = keys.iterator(); i.hasNext(); ) {
                String key = (String) i.next();
                Object value = req.get(key);
                Object v = null;
                if ((value.getClass().isArray())
                        && (((Object[]) value).length > 0)) {
                    if (((Object[]) value).length > 1) {
                        v = ((Object[]) value);
                    } else {
                        v = ((Object[]) value)[0];
                    }
                } else {
                    v = value;
                }
                if ((v != null) && ((v instanceof String)) && !"\"\"".equals(v)) {
                    String s = ((String) v).trim();
                    if (s.length() > 0) {
                        p.put(key, s);
                    }
                }
            }
            hashMap.putAll(p);
            // 读取cookie
            hashMap.putAll(ReadCookieMap(request));

        }
        return hashMap;
    }

    /**
     * 得到页面传递的参数封装成map
     */

    public Map<String, String> getParameters(HttpServletRequest request) {
        if (request == null) {
            request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        }
        Map<String, String> p = new HashMap<String, String>();
        Map req = request.getParameterMap();
        if ((req != null) && (!req.isEmpty())) {

            Collection keys = req.keySet();
            for (Iterator i = keys.iterator(); i.hasNext(); ) {
                String key = (String) i.next();
                Object value = req.get(key);
                Object v = null;
                if ((value.getClass().isArray())
                        && (((Object[]) value).length > 0)) {
                    v = ((Object[]) value)[0];
                } else {
                    v = value;
                }
                if ((v != null) && ((v instanceof String)) && !"\"\"".equals(v)) {
                    String s = (String) v;
                    if (s.length() > 0) {
                        p.put(key, s);
                    }
                }
            }
            //读取cookie
            p.putAll(ReadCookieMap(request));
            return p;
        }
        return p;
    }

    /**
     * 将cookie封装到Map里面
     *
     * @param request
     * @return
     */
    private static Map<String, String> ReadCookieMap(HttpServletRequest request) {
        Map<String, String> cookieMap = new HashMap<String, String>();
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                cookieMap.put(cookie.getName(), cookie.getValue());
            }
        }
        return cookieMap;
    }

    /**
     * 输出json
     *
     * @param response
     * @param
     */
    public void toObjectJson(HttpServletResponse response, String json) {
        PrintWriter out = null;
        try {
            response.setContentType("application/json; charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            out = response.getWriter();
            out.print(json);
            out.flush();
            out.close();
        } catch (Exception e) {
            LOG.info(e.getMessage(), e);
        } finally {
            out.close();
        }
    }

    /**
     * 从redis获取到登录对象（后台用户）
     * @return
     */
    public PlatformUser redisPlatformUser(HttpServletRequest request){
        //判断用户是否登录
        String token = request.getHeader("Authorization");
        String user = redisUtil.get(Constant.TOKEN+token);
        PlatformUser platformUser = JSONObject.parseObject(user, PlatformUser.class);
        return platformUser;
    }

    /**
     * 从redis获取到登录对象（APP）
     * @return
     */
    public UserInfo redisUser(HttpServletRequest request){
        //判断用户是否登录
        String token = request.getHeader("Authorization");
        String user = redisUtil.get(Constant.TOKEN+token);
        UserInfo userInfo = JSONObject.parseObject(user, UserInfo.class);
        return userInfo;
    }
}
